<!-- 游戏编辑弹窗 -->
<template>
  <el-dialog :title="isUpdate ? '修改游戏' : '添加游戏'" :visible="visible" width="50%" :destroy-on-close="true"
             :before-close="confirmClose" @update:visible="updateVisible" :close-on-click-modal="false">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" style="margin: 10px 30px">
      <el-row :gutter="18">
        <el-col :sm="12">
          <el-form-item label="游戏名称:" prop="game_name">
            <el-input v-model="form.game_name" placeholder="请输入游戏名称" clearable/>
          </el-form-item>

          <el-form-item label="icon:" prop="icon">
            <uploadImage :limit="1" v-model="form.icon"></uploadImage>
          </el-form-item>
          <el-form-item label="游戏版本:" prop="version">
            <el-input v-model="form.version" placeholder="请输入游戏版本" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="游戏状态:">
            <el-radio-group v-model="form.status">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="2">禁用</el-radio>
              <el-radio :label="3">待开服</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="游戏类目:" prop="cate_ids">
            <PageSelect :placeholder="'请选择游戏类目'" v-model="form.cate_ids" :whereName="'name'" :url="'/boxGameCate/index'"
                        :optionLable="'name'" :optionvalue="'id'" :multiple="true" />
          </el-form-item>

          <el-form-item label="白名单:" prop="white">
            <el-input v-model="form.white" placeholder="白名单" clearable/>
          </el-form-item>

          <el-form-item label="备注:" prop="desc">
            <el-input v-model="form.desc" placeholder="备注" clearable/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="游戏描述:" prop="content" style="margin-top: 15px;">
            <el-input type="textarea" v-model="form.content" placeholder="请输入游戏描述" clearable/>
          </el-form-item>
          <el-form-item label="游戏信息:" prop="game_info">
            <tinymce-editor v-model="form.game_info" :init="initEditor"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button @click="confirmClose()">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import setting from '@/config/setting'

import uploadImage from "@/components/uploadImage";
import PageSelect from "@/components/pageSelect/index.vue";
import TinymceEditor from "@/components/TinymceEditor";

export default {
  name: "BoxGameEdit",
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object,
  },
  components: {uploadImage, TinymceEditor,PageSelect},

  data() {
    return {
      setting: setting,
      videomsg: {
        url: "",
        name: "",
      },
      direction: "rtl",
      // 表单数据
      form: Object.assign({status: 1}, this.data),
      where: {},
      // 表单验证规则
      rules: {
        game_name: [{ required: true, message: "请输入游戏名称", trigger: "blur" }],
        name: [{ required: true, message: "请输入游戏分类名称", trigger: "blur" },],
        icon: [{ required: true, message: "请输入上传icon", trigger: "blur" }],
        cate_ids: [{ required: true, message: "请选择游戏类目", trigger: "blur" },],
        status: [{required: true,message: "请输入状态",trigger: "blur"}],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      project: process.env.VUE_APP_PROJECT_NAMES,

    };
  },
  watch: {
    visible(val) {
      if (val) {
        if (this.data) {
          this.isUpdate = true;
          console.log(this.data,'data')
          this.form = Object.assign({}, this.data,{
            cate_ids: this.data.cate.map((d) => d.id)
          });
        } else {
          this.form = {};
          this.form.game_info = ""
          this.isUpdate = false;
        }
      }
    }
  },
  computed: {
    // 初始化富文本
    initEditor() {
      return {
        height: 300,
        branding: false,
        skin_url: "/tinymce/skins/ui/oxide",
        content_css: "/tinymce/skins/content/default/content.css",
        language_url: "/tinymce/langs/zh_CN.js",
        language: "zh_CN",
        plugins:
          "code print preview fullscreen paste searchreplace save autosave link autolink image imagetools media table codesample lists advlist hr charmap emoticons anchor directionality pagebreak quickbars nonbreaking visualblocks visualchars wordcount",
        toolbar:
          "fullscreen preview code | undo redo | forecolor backcolor | bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | outdent indent | numlist bullist | formatselect fontselect fontsizeselect | link image media emoticons charmap anchor pagebreak codesample | ltr rtl",
        toolbar_drawer: "sliding",
        images_upload_handler: (blobInfo, success, error) => {
          let file = blobInfo.blob();
          // 使用axios上传
          const formData = new FormData();
          formData.append("file", file, file.name);
          this.$http
            .post("/upload/uploadImageOss", formData)
            .then((res) => {
              if (res.data.code == 0) {
                success(res.data.data);
              } else {
                error(res.data.msg);
              }
            })
            .catch((e) => {
              console.error(e);
              error(e.message);
            });
        },
        file_picker_types: "media",
        media_live_embeds: true,

        file_picker_callback: (callback) => {
          // file_picker_callback: (callback) => {
          const input = document.createElement("input");
          input.setAttribute("type", "file");
          const that = this; // 为 Vue 构造函数中的 this，指向 Vue 实例对象
          input.onchange = async function () {
            const file = this.files[0]; // 为 HTMLInputElement 构造函数中的 this，指向 input 实例对象
            const isValid = await that.validateVideo(file);

            if (isValid) {
              const loading = that.$loading({
                lock: true,
                text: "Loading",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
              });
              that.uploadFile(file, "video");
              // loading.show();
              setTimeout(() => {
                loading.close();
                // console.log(that.videomsg.url,888888888888)
                if (that.videomsg.url != "") {
                  callback(that.videomsg.url);
                }
                // console.log(that.location + "lab/" + that.videomsg.url);
              }, 2000);
              // const { url } = await that.uploadFile(file, "video");
              // callback(url);
            } else {
              callback();
            }
          };

          input.click();
        },

      };
    },
  },
  methods: {
    //校验视频格式和内存大小
    validateVideo(file) {
      const isMP4 = file.type === "video/mp4";
      // const isLt3M = file.size / 1024 / 1024 < 5;

      if (!isMP4) {
        this.$message.error("上传视频必须为 MP4 格式！");

        return false;
      }
      return true;
    },

    //上传视频
    uploadFile(file, folder = "images") {
      const formData = new FormData();
      formData.append("file", file);
      this.$http.post("/upload/uploadImageOss", formData).then((res) => {
        // console.log(res.data.data, " res.data.data");
        console.log(folder, 'folder')
        if (res.data.code == 0) {
          this.videomsg.url = res.data.data;
          this.videomsg.name = file.name;
        } else {
          this.$message({
            message: res.message,
            type: "error",
            duration: "5000",
          });
        }
      });
    },
    save() {
      delete this.form.app_id;
      this.$refs["form"].validate((valid) => {
        this.form.cate_id = this.form.cate_ids.join(',');
        delete this.form.cate_ids;
        if (valid) {
          this.loading = true;
          this.$http
            .post("/boxGame/edit", this.form)
            .then((res) => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                if (!this.isUpdate) {
                  this.form = {};
                }
                this.updateVisible(false);
                this.$emit("done");
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit("update:visible", value);
    },

    confirmClose() {
      this.$confirm("确定要返回吗？", "温馨提示")
        .then(() => {
          this.updateVisible(false);
          this.initForm();
        })
        .catch(() => {
        });
    },
    initForm() {
      this.checkAll = false
      this.checkedCities = [];
      this.form = {}
      return this.form
    },
  },
};
</script>

<style scoped></style>
